package storage.record;

import java.util.HashMap;
import java.util.Map;

import static storage.file.Page.*;
import static storage.sql.Types.*;

public class TableInfo {
	private Schema schema;
	private Map<String,Integer> offsets;
	private int recordlen;
	private String tblname;
	
	public TableInfo(String tblname, Schema sch){
		this.schema = sch;
		this.tblname = tblname;
		this.offsets = new HashMap<String, Integer>();
		int pos = 0;
		for(String fldname: schema.fields()){
			offsets.put(fldname, pos);
			pos += lengthInBytes(fldname);
		}
		this.recordlen = pos;
	}

	public TableInfo(String tblname, Schema sch, Map<String,Integer> offsets, int recordlen){
		this.schema = sch;
		this.tblname = tblname;
		this.offsets = offsets;
		this.recordlen = recordlen;
	}
	
	public String fileName(){
		return this.tblname + ".tbl";
	}
	
	public Schema schema(){
		return this.schema;
	}
	
	public int offset(String fldname){
		return offsets.get(fldname);
	}
	
	public int recordLength(){
		return this.recordlen;
	}
	
	private int lengthInBytes(String fldname){
		int fldtype = schema.type(fldname);
		if (fldtype == INTEGER)
			return INT_SIZE;
		else if (fldtype == DATE)
			return STR_SIZE(10);
		else if (fldtype == TIME)
			return STR_SIZE(8);
		else
			return STR_SIZE(schema.length(fldname));
	}
}
